import { ref, reactive, computed } from 'vue'
import { toast } from '@/composables/util'
// 列表、分页、搜索、删除、修改状态
export const useInitTable = (option = {}) => {
  // 获取浏览器可视高度 或 Body 的可视高度
  const windowHeight = ref(window.innerHeight || document.body.clientHeight)
  // 表格数据
  const tableData = ref([])
  // 加载动画
  const loading = ref(false)
  // 当前页码
  const currentPage = ref(1)
  // 总条数
  const total = ref(0)
  // 每页条数
  const limit = 10
  // 搜索表单
  let searchForm = null
  // 重置表单
  let resetSearchForm = null
  // 多选选中ID
  const multiSelectionIds = ref([])

  const circleUrl =
    'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  // 表格节点
  const tableRef = ref(null)
  if (option.searchForm) {
    searchForm = reactive({ ...option.searchForm })
    resetSearchForm = () => {
      for (const key in option.searchForm) {
        searchForm[key] = option.searchForm[key]
      }
      getData()
    }
  }

  // 获取表格数据
  const getData = async (page = null) => {
    if (typeof page === 'number') currentPage.value = page
    loading.value = true
    const res = await option.getList(currentPage.value, searchForm)
    if (option.onGetList && typeof option.onGetList === 'function') {
      option.onGetList(res)
    } else {
      tableData.value = res.list
      total.value = res.totalCount
    }
    loading.value = false
  }
  getData()

  // 删除
  const handleDelete = async id => {
    try {
      loading.value = true
      await option.delete(id)
      toast('删除成功')
      getData()
    } finally {
      loading.value = false
    }
  }

  // 修改状态
  const handleStatusChange = async (status, row) => {
    row.statusLoading = true
    await option.updateStatus(row.id, status)
    toast('修改状态成功')
    row.status = status
    row.statusLoading = false
    await getData()
  }

  // 表格选中事件
  const handleSelectionChange = e => {
    multiSelectionIds.value = e.map(v => v.id)
  }

  // 批量删除
  const handleMultiDelete = async () => {
    try {
      loading.value = true
      await option.delete(multiSelectionIds.value)
      toast("删除成功")
      if (tableRef.value) {
        tableRef.value.clearSelection()
      }
      getData()
    } finally {
      loading.value = false
    }
  }

  // 批量修改状态
  const handleMultiStatusChange = async status => {
    try {
      loading.value = true
      await option.updateStatus(multiSelectionIds.value, status)
      toast("修改状态成功")
      if (tableRef.value) {
        tableRef.value.clearSelection()
      }
      getData()
    } finally {
      loading.value = false
    }
  }

  return {
    windowHeight,
    searchForm,
    tableData,
    loading,
    currentPage,
    total,
    limit,
    tableRef,
    multiSelectionIds,
    circleUrl,
    toast,
    resetSearchForm,
    getData,
    handleDelete,
    handleStatusChange,
    handleSelectionChange,
    handleMultiDelete,
    handleMultiStatusChange
  }
}

// 新增、修改
export const useInitForm = (option = {}) => {
  // 表单默认值
  const defaultForm = option.form
  // 表单
  const form = reactive({})
  // 弹窗节点
  const dialogRef = ref(null)
  // 表单节点
  const formRef = ref(null)
  // 新增/编辑标识
  const EditID = ref(0)
  // 校验规则
  const rules = option.rules || {}
  // 弹窗标题
  const dialogTitle = computed(() => (EditID.value ? "修改" : "新增"))

  // 提交
  const handleSubmit = () => {
    formRef.value.validate(async val => {
      if (!val) return
      dialogRef.value.showLoading()
      let body = {}
      if (option.beforeSubmit && typeof option.beforeSubmit === 'function') {
        body = option.beforeSubmit({ ...form })
      } else {
        body = form
      }
      try {
        EditID.value ? await option.updata(EditID.value, body) : await option.create(body)
        toast(`${dialogTitle.value}成功！`)
        option.getData(EditID.value ? false : 1)
        dialogRef.value.close()
      } finally {
        dialogRef.value.hideLoading()
      }
    })
  }

  // 重置表单
  const resetForm = (row = false) => {
    if (formRef.value) formRef.value.clearValidate()
    for (const key in defaultForm) {
      form[key] = row[key]
    }
  }

  // 新增
  const handleCreate = () => {
    EditID.value = 0
    resetForm(defaultForm)
    dialogRef.value.open()
  }

  // 修改
  const handleEdit = async row => {
    EditID.value = row.id
    resetForm(row)
    dialogRef.value.open()
  }

  return {
    form,
    dialogRef,
    formRef,
    EditID,
    rules,
    dialogTitle,
    handleSubmit,
    resetForm,
    handleCreate,
    handleEdit,
  }
}
